package com.zhoug.zxing.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.zhoug.zxing.activity.CaptureActivity;

import androidx.fragment.app.Fragment;

/**
 * @Author 35574
 * @Date 2020/6/28
 * @Description
 */
public class ZxingHelper {
    private static final String TAG = ">>>ZxingHelper";
    private Callback callback;
    private Activity activity;
    private Fragment fragment;

    public ZxingHelper(Activity activity) {
        this.activity = activity;
    }

    public ZxingHelper(Fragment fragment) {
        this.fragment = fragment;
    }


    public void start() {
        if (fragment != null) {
            Intent intent = new Intent(fragment.getContext(), CaptureActivity.class);
            fragment.startActivityForResult(intent, 1001);
        } else if (activity != null) {
            Intent intent = new Intent(activity, CaptureActivity.class);
            activity.startActivityForResult(intent, 1001);
        }else{
            Log.e(TAG, "fragmentc and activity all null");
        }
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 1001) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    callback.result(Callback.CODE_FAIL, "扫码错误");
                } else {
                    String result = bundle.getString("result");
                    callback.result(Callback.CODE_SUCCESS, result);
                }
            } else {
                callback.result(Callback.CODE_FAIL, "扫码失败");
            }
        }
    }


    public Callback getCallback() {
        return callback;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback {
        int CODE_SUCCESS = 2;
        int CODE_FAIL = 1;

        /**
         * @param code {@link #CODE_FAIL,#CODE_SUCCESS}
         * @param msg
         */
        void result(int code, String msg);
    }
}
